#include "RedGunState.h"

RedGunState::RedGunState(ArmyData* data) {
	_armyData = data;
	_counter = 0;
	_currentEffectIndex;
	_inRangeCounter = _outRangeCounter = 0;
	_isDisable = false;
	_armyData->isHalf = true;
}

void RedGunState::initSprites() {
	_armyData->initSpriteHandler();
	_armyData->sprites->addSprite(1, _ID_ARMY_GUN_2, 0);
	_armyData->sprites->setState(1);
}

void RedGunState::updateIsInRange() {
	_armyData->canInteract = true;
	_inRangeCounter++;
	if (_inRangeCounter == 1) {
		_isDisable = false;
		setCurrentIndex(0);
		_counter = 0;
	}
	if (_currentStateIndex == 0 && _counter > _RED_GUN_FR) {
		setCurrentIndex(1);
	} else if (_currentStateIndex == 1 && _counter > _RED_GUN_FR * 2){
		setCurrentIndex(2);
	} else if (_currentStateIndex >= 2){
		if (_armyData->targetRect->X < _armyData->getRect()->X) {
			_tempData = (_armyData->targetRect->Y - _armyData->rect->Y) / abs(_armyData->rect->X - _armyData->targetRect->X);
			if (_tempData > 0.3) {
				if (_tempData > 1) {
					setCurrentIndex(4);
				} else {
					setCurrentIndex(3);
				}
			} else {
				setCurrentIndex(2);
			}
		}
	}
}

void RedGunState::updateIsOutRange() {
	_outRangeCounter++;
	if (_outRangeCounter == 1) {
		setCurrentIndex(5);
		_counter = 0;
	}
	if (_currentStateIndex == 5 && _counter > _RED_GUN_FR) {
		setCurrentIndex(6);
	} else if (_currentStateIndex == 6 && _counter > _RED_GUN_FR * 3) {
		_isDisable = true;
		_armyData->canInteract = false;
	}
}

void RedGunState::update(long timetick) {
	if (_armyData->isDead) return;
	// if player in range, gun will update the first 3 sprite
	if (_armyData->_checkInRange() && _armyData->checkTargetAhead()) {
		_outRangeCounter = 0;
		updateIsInRange();
	} else {
		// if player not in range, gun with re-update to hide
		//setCurrentIndex(5);
		_inRangeCounter = 0;
		updateIsOutRange();
	}
	updateCurrentSprite();
}

void RedGunState::updateCurrentSprite() {
	_counter = _counter > 149 ? 0 : _counter + 1;
	if (_counter % 10 == 0) {
		_currentEffectIndex = (_currentEffectIndex + 1)  % 3;
		_armyData->sprites->currentSprite->setIndex(_currentStateIndex + _currentEffectIndex * 7);
	}
}

void RedGunState::setCurrentIndex(int index) {
	_currentStateIndex = index;
}

void RedGunState::draw(long timetick) {
	if (!_isDisable) {
		_armyData->sprites->draw();
		_armyData->bulletContainer->draw(timetick);
	}
}